package com.store.app.activity;

import android.app.Activity;
import android.app.AlertDialog;
import android.app.Dialog;
import android.content.ActivityNotFoundException;
import android.content.DialogInterface;
import android.content.Intent;
import android.net.Uri;
import android.os.Bundle;
import android.os.Environment;
import android.provider.MediaStore;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.text.TextUtils;
import android.util.Log;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.CheckBox;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.RelativeLayout;
import android.widget.Spinner;
import android.widget.TextView;
import android.widget.Toast;

import com.hyphenate.easeui.widget.EaseSwitchButton;
import com.store.app.BaseActivity;
import com.store.app.ExitApplication;
import com.store.app.R;
import com.store.app.adapter.AddGoodsRVAdapter;
import com.store.app.bean.BitmapBean;
import com.store.app.bean.EventBusBean;
import com.store.app.bean.GoodsBean;
import com.store.app.bean.PosterBean;
import com.store.app.dialog.SetGoodTypeDialog;
import com.store.app.imlife.utils.ToastTools;
import com.store.app.net.NetRequest;
import com.store.app.net.ifc.IOnHttpListener;
import com.store.app.utils.MoneyUtil;
import com.store.app.utils.SettingData;
import com.store.app.utils.UtilsBitmap;
import com.yalantis.ucrop.CropUtils;
import com.yalantis.ucrop.UCrop;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import java.io.File;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;

import de.greenrobot.event.EventBus;

/**
 * Created by Administrator on 2016/12/15.
 * 添加商品页面（手动添加跟扫码添加）
 */
public class AddGoodNewActivity extends BaseActivity implements View.OnClickListener, IOnHttpListener {
    private TextView tv_submit;                                     //提交
    private EditText et_name;                                       //名称
    private EditText et_barcode;                                    //条码
    private Spinner spinner;                                        //分类
    private EditText et_price;                                      //售价
    private TextView tv_cost;                                       //进价(不可编辑)
    private EditText et_return_money;                               //返利
    private EditText et_shelf_life;                                 //保质期
    private EditText et_stock_call;                                 //库存预警
    private EditText et_vender;                                     //厂家
    private EditText et_time_call;                                  //临期预警
    private EaseSwitchButton sw_to_cashier;                                   //是否收藏到收银台
    private EaseSwitchButton sw_to_local_life;                                //是否支持网店销售（本地生活）
    private EaseSwitchButton sw_discount;                                     //是否参与促销活动
    private EaseSwitchButton sw_weight;
    private CheckBox cb_weight;                                              //是否称重计量
    private TextView tvTitle;                                       //标题
    private ImageView public_ll_return;                             //返回

    //===========================================新增字段 start============================================================//
    private RecyclerView rv_show_goods_pic;                        //显示添加的商品图片
    private ImageView iv_add_pic;                                  //添加商品图片
    private EditText et_own_code;       //自编码
    private EditText et_mnemonic_code;                            //助记码
    //    private TextView tv_sale_unit;                                 //销售单位
    private Spinner spinner_select_sale_unit;                      //选择销售单位
    private TextView tv_purchase_unit;                             //采购单位
    private Spinner spinner_select_purchase_unit;                  //选择采购单位
    private TextView tv_min_package_unit;                          //最小包装单位
    private Spinner spinner_select_min_package_unit;               //选择最小包装单位
    private RelativeLayout rl_conversion;                            //换算关系
    private TextView tv_conversion;                                //显示换算关系
    private TextView tv_expiration_date_unit;                      //保质期单位
    private Spinner spinner_select_expiration_date_unit;           //选择保质期单位
    private EditText et_location;                                  //陈列位
    private EditText et_purchase_price_specifications;             //进价规格
    private EditText et_price_specifications;                      //售价规格
    private EditText et_discount;                                 //折扣
    private EditText et_gross_profit;                             //毛利
    private TextView tv_date_unit;                                //临期预警时间单位
    private Spinner spinner_select_date_unit;                      //选择临期预警时间单位
    private EaseSwitchButton sw_to_ad_recommend;                   //广告推荐
    private TextView tv_cancel;                                    //取消

    //===========================================新增字段 end============================================================//


    private String mGoodsCategory;                                      //商品类别
    private BitmapBean bitmapBean;
    private NetRequest netRequest;
    private Dialog dialog;
    private static final int FLAG_CHOOSE_IMG = 5;
    private static final int FLAG_CHOOSE_PHONE = 6;
    private static final int FLAG_DETIALS = 99;
    private static String localTempImageFileName = "";

    private List<String> keyData = new ArrayList<String>();
    private List<String> valueData = new ArrayList<String>();
    private List<Map<String, String>> mDatas = new ArrayList<Map<String, String>>();

    private GoodsBean bean;
    private String barcode;

    private String desc1;//详情描述
    private String image_detail;//图片详情，用来提交给服务器
    private List<PosterBean> posterList;  //用来显示详情里面图文信息

    private List<BitmapBean> mUploadBitmapBeans;//上传图片列表
    private AddGoodsRVAdapter mAddGoodsRVAdapter;

    private static final int FLAG_ADD_PIC = 0;//添加图片
    private static final int FLAG_MODIFY_PIC = 1;//修改图片
    private int mPicFlag = FLAG_ADD_PIC;//区分是添加图片还是修改图片

    private int mModifyPicPosition;//要修改的图片的位置
    private String mSaleUnit;
    private String mPurchaseUnit;
    private String mMinPackageUnit;
    private SetGoodTypeDialog conversionDialog;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        ExitApplication.getInstance().addActivity(this);
        setContentView(R.layout.activity_add_goods_xgp);

        if (getIntent() != null) {
            if (getIntent().getSerializableExtra("goods_bean") != null) {
                bean = (GoodsBean) getIntent().getSerializableExtra("goods_bean");
            }
            if (getIntent().getStringExtra("barcode") != null) {
                barcode = getIntent().getStringExtra("barcode");
            }
        }
        initView();
        initData();
    }


    private void initData() {
        tvTitle.setText("添加商品");

        initRecyclerView();

        netRequest = new NetRequest(this);
        netRequest.requestTypeList(1);
        netRequest.requestSpecificationUnitFind(5);
        //请求自编码接口
        netRequest.requestZBM(6);
        if (bean != null) {
            //名称
            String s_name = bean.getItem_name().trim();
            if (!TextUtils.isEmpty(s_name) && !s_name.equals("null")) {
                et_name.setText(s_name);
            }
            //条码
            String s_barcode = bean.getBarcode().trim();
            if (!TextUtils.isEmpty(s_barcode) && !s_barcode.equals("null")) {
                et_barcode.setText(s_barcode);
            }

            /*String s_ecost = bean.getCost_price() + "".trim();
            if (!TextUtils.isEmpty(s_ecost) && !s_ecost.equals("null")) {
                tv_cost.setText(s_ecost);
            }*/
            //售价
            String s_eprice = bean.getMarket_price() + "".trim();
            if (!TextUtils.isEmpty(s_eprice) && !s_eprice.equals("null")) {
                et_price.setText(s_eprice);
            }

            //保质期
            String s_expir = bean.getDurability_period() + "".trim();
            Log.v("zyl", "保质期为：" + s_expir);
            if (!TextUtils.isEmpty(s_expir) && !s_expir.equals("null") && !(s_expir.equals("0"))) {
                et_shelf_life.setText(s_expir);
            }
        } else if (!TextUtils.isEmpty(barcode)) {
            if (!TextUtils.isEmpty(barcode) && !barcode.equals("null")) {
                et_barcode.setText(barcode);
            }
        }

    }

    /**
     * 选择销售单位
     */
    private void initSaleUnitSpinner() {
        ArrayAdapter<String> adapter = new ArrayAdapter<String>(this, R.layout.item_spinner, mUnits);
        adapter.setDropDownViewResource(R.layout.item_spinner);
        spinner_select_sale_unit.setAdapter(adapter);
        spinner_select_sale_unit.setSelection(mUnits.indexOf("包") == -1 ? 0 : mUnits.indexOf("包"));
        spinner_select_sale_unit.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {

            @Override
            public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
                mSaleUnit = mUnits.get(position);
            }

            @Override
            public void onNothingSelected(AdapterView<?> parent) {

            }
        });
    }

    /**
     * 选择采购单位
     */
    private void initPurchaseUnitSpinner() {
        ArrayAdapter<String> adapter = new ArrayAdapter<String>(this, R.layout.item_spinner, mUnits);
        adapter.setDropDownViewResource(R.layout.item_spinner);
        spinner_select_purchase_unit.setAdapter(adapter);
        spinner_select_purchase_unit.setSelection(mUnits.indexOf("箱") == -1 ? 0 : mUnits.indexOf("箱"));

        spinner_select_purchase_unit.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {

            @Override
            public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
                mPurchaseUnit = mUnits.get(position);
            }

            @Override
            public void onNothingSelected(AdapterView<?> parent) {

            }
        });
    }

    /**
     * 选择最小包装单位
     */
    private void initMinPackageUnitSpinner() {
        ArrayAdapter<String> adapter = new ArrayAdapter<String>(this, R.layout.item_spinner, mUnits);
        adapter.setDropDownViewResource(R.layout.item_spinner);
        spinner_select_min_package_unit.setAdapter(adapter);
        spinner_select_min_package_unit.setSelection(mUnits.indexOf("支") == -1 ? 0 : mUnits.indexOf("支"));

        spinner_select_min_package_unit.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {

            @Override
            public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
                mMinPackageUnit = mUnits.get(position);
            }

            @Override
            public void onNothingSelected(AdapterView<?> parent) {

            }
        });
    }

    /**
     * 初始化显示图片列表的RecyclerView
     */
    private void initRecyclerView() {
        mUploadBitmapBeans = new ArrayList<>();
        rv_show_goods_pic.setLayoutManager(new LinearLayoutManager(this, LinearLayoutManager.HORIZONTAL, false));
        //rv_show_goods_pic.addItemDecoration(new RecycleViewDivider(this,LinearLayoutManager.VERTICAL, Utils.dip2px(this,4), Color.RED));
        mAddGoodsRVAdapter = new AddGoodsRVAdapter(this, mUploadBitmapBeans);
        rv_show_goods_pic.setAdapter(mAddGoodsRVAdapter);

        mAddGoodsRVAdapter.setOnPicItemClickListener(new AddGoodsRVAdapter.OnPicItemClickListener() {
            @Override
            public void onPicItemClick(int position) {
                mModifyPicPosition = position;
                mPicFlag = FLAG_MODIFY_PIC;
                getPic();
            }
        });
    }

    private void initView() {
        //===========================================新增字段 start============================================================//
        rv_show_goods_pic = (RecyclerView) findViewById(R.id.rv_show_goods_pic);
        iv_add_pic = (ImageView) findViewById(R.id.iv_add_pic);
        et_mnemonic_code = (EditText) findViewById(R.id.et_mnemonic_code);
        spinner_select_sale_unit = (Spinner) findViewById(R.id.spinner_select_sale_unit);
        tv_purchase_unit = (TextView) findViewById(R.id.tv_purchase_unit);
        spinner_select_purchase_unit = (Spinner) findViewById(R.id.spinner_select_purchase_unit);
        tv_min_package_unit = (TextView) findViewById(R.id.tv_min_package_unit);
        spinner_select_min_package_unit = (Spinner) findViewById(R.id.spinner_select_min_package_unit);
        rl_conversion = (RelativeLayout) findViewById(R.id.ll_conversion);
        tv_conversion = (TextView) findViewById(R.id.tv_conversion);
        tv_expiration_date_unit = (TextView) findViewById(R.id.tv_expiration_date_unit);
        spinner_select_expiration_date_unit = (Spinner) findViewById(R.id.spinner_select_expiration_date_unit);
        et_location = (EditText) findViewById(R.id.et_location);
        et_purchase_price_specifications = (EditText) findViewById(R.id.et_purchase_price_specifications);
        et_price_specifications = (EditText) findViewById(R.id.et_price_specifications);
        et_discount = (EditText) findViewById(R.id.et_discount);
        et_gross_profit = (EditText) findViewById(R.id.et_gross_profit);
        tv_date_unit = (TextView) findViewById(R.id.tv_date_unit);
        spinner_select_date_unit = (Spinner) findViewById(R.id.spinner_select_date_unit);
        sw_to_ad_recommend = (EaseSwitchButton) findViewById(R.id.sw_to_ad_recommend);
        tv_cancel = (TextView) findViewById(R.id.tv_cancel);

        iv_add_pic.setOnClickListener(this);
        rl_conversion.setOnClickListener(this);

        sw_to_ad_recommend.closeSwitch();
        sw_to_ad_recommend.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (sw_to_ad_recommend.isSwitchOpen()) {
                    sw_to_ad_recommend.closeSwitch();
                } else {
                    sw_to_ad_recommend.openSwitch();
                }
            }
        });

        tv_cancel.setOnClickListener(this);

        //===========================================新增字段 end============================================================//

        tv_submit = (TextView) findViewById(R.id.tv_submit);
        public_ll_return = (ImageView) findViewById(R.id.public_ll_return);
        tvTitle = (TextView) findViewById(R.id.tvTitle);
        et_name = (EditText) findViewById(R.id.et_name);
        et_barcode = (EditText) findViewById(R.id.et_barcode);
        spinner = (Spinner) findViewById(R.id.spinner);
        et_price = (EditText) findViewById(R.id.et_price);
        tv_cost = (TextView) findViewById(R.id.tv_cost);
        et_return_money = (EditText) findViewById(R.id.et_return_money);
        et_shelf_life = (EditText) findViewById(R.id.et_shelf_life);
        sw_to_cashier = (EaseSwitchButton) findViewById(R.id.sw_to_cashier);
        sw_to_cashier.closeSwitch();
        sw_to_cashier.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (sw_to_cashier.isSwitchOpen()) {
                    sw_to_cashier.closeSwitch();
                } else {
                    sw_to_cashier.openSwitch();
                }
            }
        });
        sw_to_local_life = (EaseSwitchButton) findViewById(R.id.sw_to_local_life);
        sw_to_local_life.closeSwitch();
        sw_to_local_life.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (sw_to_local_life.isSwitchOpen()) {
                    sw_to_local_life.closeSwitch();
                } else {
                    sw_to_local_life.openSwitch();
                }
            }
        });
        tv_submit.setOnClickListener(this);
        public_ll_return.setOnClickListener(this);

        spinner.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {

            @Override
            public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
                mGoodsCategory = keyData.get(position);
            }

            @Override
            public void onNothingSelected(AdapterView<?> parent) {

            }
        });
        cb_weight = (CheckBox) findViewById(R.id.cb_weight);
        et_stock_call = (EditText) findViewById(R.id.et_stock_call);
        et_stock_call.setOnClickListener(this);
        et_vender = (EditText) findViewById(R.id.et_vender);
        et_vender.setOnClickListener(this);
        et_time_call = (EditText) findViewById(R.id.et_time_call);
        sw_discount = (EaseSwitchButton) findViewById(R.id.sw_discount);
        sw_discount.openSwitch();//默认是
        sw_discount.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (sw_discount.isSwitchOpen()) {
                    sw_discount.closeSwitch();
                } else {
                    sw_discount.openSwitch();
                }
            }
        });

        et_own_code = (EditText) findViewById(R.id.et_own_code);
    }

    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.tv_submit:
                submit();
                break;
            case R.id.public_ll_return:
                finish();
                break;
            case R.id.iv_add_pic:
                mPicFlag = FLAG_ADD_PIC;
                getPic();
                break;
            case R.id.ll_conversion:
                showConversionDialog();
                break;
            case R.id.tv_cancel:
                finish();
                break;
        }
    }

    private String mCgdwNum;//采购单位数量
    private String mXsdwNum;//销售单位数量
    private String mZxbzNum;//最小包装单位数量

    private void showConversionDialog() {
        conversionDialog = new SetGoodTypeDialog(this, new SetGoodTypeDialog.onConfirmListener() {
            @Override
            public void onConfirm(String cgdwNum, String xsdwNum, String zxbzNum) {
                showConversion(cgdwNum, xsdwNum, zxbzNum);
                mCgdwNum = cgdwNum;
                mXsdwNum = xsdwNum;
                mZxbzNum = zxbzNum;

                //设置进价规格和售价规格
                et_purchase_price_specifications.setText(mPurchaseUnit + "(" + xsdwNum + mSaleUnit + ")");
                et_price_specifications.setText(mSaleUnit + "(" + Integer.parseInt(zxbzNum) / Integer.parseInt(xsdwNum) + mMinPackageUnit + ")");
            }
        });
        conversionDialog.show();
        conversionDialog.setTypeText(mPurchaseUnit, mSaleUnit, mMinPackageUnit, mSaleUnit);

    }

    //显示换算关系
    private void showConversion(String cgdwNum, String xsdwNum, String zxbzNum) {
        tv_conversion.setText(cgdwNum + mPurchaseUnit + "=" + xsdwNum + mSaleUnit + "=" + zxbzNum + mMinPackageUnit);
    }

    public void getPic() {
        if (dialog != null && dialog.isShowing()) {
            return;
        }
        dialog = new AlertDialog.Builder(AddGoodNewActivity.this)
                .setTitle("请选择图片来源")
                .setItems(new String[]{"相册", "相机"},
                        new DialogInterface.OnClickListener() {

                            @Override
                            public void onClick(DialogInterface dialog,
                                                int which) {
                                if (which == 0) {
                                    Intent intent = new Intent(
                                            Intent.ACTION_PICK, MediaStore.Images.Media.EXTERNAL_CONTENT_URI);
                                    startActivityForResult(intent,
                                            FLAG_CHOOSE_IMG);
                                } else if (which == 1) {
                                    String status = Environment
                                            .getExternalStorageState();
                                    if (status
                                            .equals(Environment.MEDIA_MOUNTED)) {
                                        try {
                                            localTempImageFileName = "";
                                            localTempImageFileName = String
                                                    .valueOf((new Date())
                                                            .getTime())
                                                    + ".png";
                                            File filePath = SettingData.FILE_PIC_SCREENSHOT;
                                            if (!filePath.exists()) {
                                                filePath.mkdirs();
                                            }
                                            Intent intent = new Intent(
                                                    MediaStore.ACTION_IMAGE_CAPTURE);
                                            File f = new File(filePath,
                                                    localTempImageFileName);
                                            // localTempImgDir和localTempImageFileName是自己定义的名字
                                            Uri u = Uri.fromFile(f);
                                            intent.putExtra(
                                                    MediaStore.Images.Media.ORIENTATION,
                                                    0);
                                            intent.putExtra(
                                                    MediaStore.EXTRA_OUTPUT,
                                                    u);
                                            startActivityForResult(
                                                    intent,
                                                    FLAG_CHOOSE_PHONE);
                                        } catch (ActivityNotFoundException e) {
                                            //
                                        }
                                    }
                                }
                            }
                        }).show();
    }

    /**
     * 提交
     */
    private void submit() {
        Log.v("zyl", "submit");
        //必填项  1.条形码 2.名称 3.售价 4.换算关系
        String picPathJsonStr = getPicPathJsonStr();                    //所有图片path的json字符串
        String ownCode = et_own_code.getText().toString().trim();       //自编码
        String barcode = et_barcode.getText().toString().trim();        //条形码
        String zjm = et_mnemonic_code.getText().toString().trim();     //助记码
        String name = et_name.getText().toString().trim();              //商品名称
        String vender = et_vender.getText().toString().trim();          //厂家
        String conversion = tv_conversion.getText().toString().trim();  //换算关系
        String swWeight = cb_weight.isChecked() ? "Y" : "N";             //称重计量
        String shelf_life = et_shelf_life.getText().toString().trim();  //保质期
        String clw = et_location.getText().toString().trim();            //陈列位
        String price = et_price.getText().toString().trim();            //售价
        String returnMoney = et_return_money.getText().toString().trim();//返现
        String discount = et_discount.getText().toString().trim();//折扣，前端取值之后需要除以100
        String time_call = et_time_call.getText().toString().trim();  //临期预警
        String stock_call = et_stock_call.getText().toString().trim();  //库存预警
        String swToAd = sw_to_ad_recommend.isSwitchOpen() ? "Y" : "N";         //是否广告推荐
        String swToCashier = sw_to_cashier.isSwitchOpen() ? "Y" : "N";         //是否收藏到收银台
        String swToLocalLife = sw_to_local_life.isSwitchOpen() ? "Y" : "N";    //是否支持网店销售
        String swDiscount = sw_discount.isSwitchOpen() ? "Y" : "N";             //是否允许促销活动


        //助记码的处理
        if (TextUtils.isEmpty(zjm)) {
            zjm = ownCode.substring(ownCode.length() - 4);
        }

        //必填项 ===  条形码
        if (TextUtils.isEmpty(barcode)) {
            ToastTools.showShort(AddGoodNewActivity.this, "请输入条形码");
            et_barcode.requestFocus();
            return;
        }

        //必填项 === 商品名称
        if (TextUtils.isEmpty(name)) {
            ToastTools.showShort(AddGoodNewActivity.this, "请输入商品名称");
            et_name.requestFocus();
            return;
        }

        //必填项 === 换算关系
        if (TextUtils.isEmpty(conversion)) {
            ToastTools.showShort(this, "请设置换算关系");
            return;

        } else {
            conversion = getConversionJsonStr();//换算关系
        }

        //必填项 === 售价
        if (TextUtils.isEmpty(price)) {
            ToastTools.showShort(AddGoodNewActivity.this, "请输入售价");
            et_price.requestFocus();
            return;
        }

        //临期预警缺省为7
        if (TextUtils.isEmpty(time_call)) {
            time_call = "0";
        }

        //库存预警限制条件：前端显示0-100，上传到服务器为0-1
        if (TextUtils.isEmpty(stock_call)) {
            stock_call = "0.00";
        } else {
            int stockCallInt = Integer.parseInt(stock_call);
            if (stockCallInt > 100) {
                showToast("库存预警需小于或等于100");
                et_stock_call.requestFocus();
                return;
            } else {
                stock_call = String.valueOf(stockCallInt / 100.00f);
            }
        }

        //返现限制条件
        if (TextUtils.isEmpty(returnMoney)) {
            returnMoney = "0.00";
        } else {
            if (!MoneyUtil.moneyComp(price, returnMoney)) {
                Toast.makeText(getApplicationContext(), "返现价格不能大于售价", Toast.LENGTH_SHORT).show();
                return;
            }
        }

        //折扣限制条件：前端显示0-100，上传到服务器为0-1
        if (TextUtils.isEmpty(discount)) {
            discount = "0.00";
        } else {
            int discountInt = Integer.parseInt(discount);
            if (discountInt > 100) {
                showToast("折扣需小于或等于100");
                et_discount.requestFocus();
                return;
            } else {
                discount = String.valueOf(discountInt / 100.00f);
            }
        }


        if (mUploadBitmapBeans.size() == 0) {
            ToastTools.showShort(AddGoodNewActivity.this, "请上传图片");
            return;
        }
        showProgressDialog("", "正在提交数据...");
        netRequest.requestAddGood(3, ownCode, barcode, zjm, name, mGoodsCategory, vender, mSaleUnit, mPurchaseUnit, mMinPackageUnit, conversion, swWeight,
                shelf_life, clw, price, returnMoney, discount, time_call, stock_call, swToAd, swToCashier, swToLocalLife, swDiscount, picPathJsonStr, mUploadBitmapBeans.get(0).getDocId()
        );

    }



    /**
     * 获取图片列表中所有图片path的json字符串
     *
     * @return
     */
    private String getPicPathJsonStr() {
        JSONArray mJsonArray = new JSONArray();
        for (BitmapBean uploadBitmapBean : mUploadBitmapBeans) {
            JSONObject jsonObject = new JSONObject();
            try {
                jsonObject.put("path", uploadBitmapBean.getPath());
            } catch (JSONException e) {
                e.printStackTrace();
            }
            mJsonArray.put(jsonObject);
        }

        return mJsonArray.toString();
    }

    /**
     * 获取换算关系的json字符串
     *
     * @return
     */
    private String getConversionJsonStr() {

        JSONObject jsonObject = new JSONObject();
        try {
            jsonObject.put("purchase_unit", mCgdwNum);
            jsonObject.put("sale_unit", mXsdwNum);
            jsonObject.put("min_pack_unit", mZxbzNum);
        } catch (JSONException e) {
            e.printStackTrace();
        }

        return jsonObject.toString();
    }


    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        //获取相册返回的结果
        if (requestCode == FLAG_CHOOSE_IMG && resultCode == RESULT_OK) {
            if (data != null) {
                Uri uri = data.getData();
                if (uri != null) {
                    CropUtils.startCropActivity(uri, AddGoodNewActivity.this, 5, 5);
                }
            }
        } else if (requestCode == FLAG_CHOOSE_PHONE && resultCode == RESULT_OK) {//获取相机返回的结果
            File f = new File(SettingData.FILE_PIC_SCREENSHOT, localTempImageFileName);
            Uri uri = Uri.fromFile(f);
            if (uri != null) {
                UtilsBitmap.getCompressUri(uri);
                CropUtils.startCropActivity(uri, AddGoodNewActivity.this, 5, 5);
            }
        }
        //拿到裁剪后的图片
        if (requestCode == UCrop.REQUEST_CROP && resultCode == RESULT_OK) {
            if (data != null) {
                final Uri resultUri = UCrop.getOutput(data);
                bitmapBean = UtilsBitmap.addFilePath3(resultUri.getPath(), this);
                if (bitmapBean.getIsBm() != null) {
                    //上传图片
                    netRequest.requestUploadPic(2, bitmapBean.getIsBm());
                }
            }
        } else if (resultCode == UCrop.RESULT_ERROR) {
            Toast.makeText(AddGoodNewActivity.this, "图片剪切失败！", Toast.LENGTH_SHORT)
                    .show();
        } else if (requestCode == FLAG_DETIALS) {
            if (resultCode == Activity.RESULT_OK) {
                desc1 = data.getStringExtra("desc1");
                image_detail = data.getStringExtra("image_detail");
                Log.v("zyl", "页面回来了 desc1：" + desc1);
                Log.v("zyl", "页面回来了 image_detail：" + image_detail);
            }
        }
    }

    @Override
    public void onAfinalFail() {
        dismissProgressDialog();
        showToast("请检查本地网络!");
    }

    private List<String> mUnits = new ArrayList<>();

    @Override
    public void onExecuteSuccess(int requestId, String result, String msg) {
        dismissProgressDialog();
        //请求商品分类列表
        if (requestId == 1) {
            try {
                JSONObject datas = new JSONObject(result);
                Iterator it = datas.keys();
                Map<String, String> map = null;
                while (it.hasNext()) {
                    map = new HashMap<String, String>();
                    String key = (String) it.next();
                    String value = datas.getString(key);
                    map.put(key, value);
                    keyData.add(key);
                    valueData.add(value);
                    mDatas.add(map);
                }
                ArrayAdapter<String> adapter = new ArrayAdapter<String>(this, R.layout.item_spinner, valueData);
                adapter.setDropDownViewResource(R.layout.item_spinner);
                spinner.setAdapter(adapter);
                spinner.setSelection(0);
            } catch (Exception e) {
                e.printStackTrace();
            }
        } else if (requestId == 2) {
            try {
                JSONObject obj = new JSONObject(result);
                String doc_id = obj.getString("doc_id");
                String doc_path = obj.getString("doc_path");
                String path = obj.getString("path");
                Log.v("zyl", "path:" + path);
                Log.v("zyl", "doc_path:" + doc_path);
                bitmapBean.setDocId(doc_id);
                bitmapBean.setDoc_path(doc_path);
                bitmapBean.setPath(path);

                if (mPicFlag == FLAG_ADD_PIC) {
                    mUploadBitmapBeans.add(bitmapBean);
                } else {
                    mUploadBitmapBeans.set(mModifyPicPosition, bitmapBean);
                }
                mAddGoodsRVAdapter.notifyDataSetChanged();

            } catch (JSONException e) {
                e.printStackTrace();
            }
        } else if (requestId == 3) {
            showToast("提交成功");
            EventBus.getDefault().post(new EventBusBean(229));//通知GoodsActivity刷新数据
            finish();
        } else if (requestId == 4) {
            netRequest.requestTypeList(1);
        } else if (requestId == 5) {
            try {
                mUnits.clear();
                JSONArray jsonArray = new JSONArray(result);
                for (int i = 0; i < jsonArray.length(); i++) {
                    JSONObject jsonObject = jsonArray.getJSONObject(i);
                    mUnits.add(jsonObject.getString("content"));
                }
                if (mUnits.size() != 0) {
                    initSaleUnitSpinner();
                    initPurchaseUnitSpinner();
                    initMinPackageUnitSpinner();
                }
            } catch (Exception e) {
                e.printStackTrace();
            }
        } else if (requestId == 6) {
            try {
                JSONObject jsonObject = new JSONObject(result);
                String goods_code = jsonObject.getString("goods_code");
                et_own_code.setText(goods_code);
                et_mnemonic_code.setText(goods_code.substring(goods_code.length() - 4));
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
    }

    @Override
    public void onExecuteFail(int requestId, String msg) {
        dismissProgressDialog();
        showToast(msg);
    }

}
